#ifndef BIN_HH_
# define BIN_HH_

# include "tbb/task_scheduler_init.h"
# include "tbb/blocked_range2d.h"
# include <SDL/SDL.h>
# include "common.hh"

class Bin
{
  Uint32	*img;

 public:
  Bin (Uint32	*img_)
    : img(img_)
    {
    }

  void operator() (const tbb::blocked_range2d<int>& r) const
  {
    for (int i = r.rows().begin(); i!= r.rows().end(); ++i)
      {
	for (int j = r.cols().begin(); j!= r.cols().end(); ++j)
	  {
	    Uint32 coul = img[i * WIDTH + j];

	    Uint8 red, green, blue;
	    SDL_GetRGB (coul, global_screen->format, &red, &green, &blue);
	    Uint8 mean = (red + green + blue) / 3;
	    if (mean < 127)
	      img[i * WIDTH + j] = SDL_MapRGB (global_screen->format, 0, 0, 0);
	    else
	      img[i * WIDTH + j] = SDL_MapRGB (global_screen->format, 255, 255, 255);
	  }
      }
    if (img == global_screen->pixels)
      {
	tbb::spin_mutex::scoped_lock lock;

	lock.acquire(global_screen_mutex);

	SDL_UpdateRect(global_screen,
		       r.cols().begin(),
		       r.rows().begin(),
		       r.cols().end() - r.cols().begin(),
		       r.rows().end() - r.rows().begin());

	lock.release();
      }
  }
};

#endif /* !BIN_HH_ */
